package com.liliudong.template.biz.service.sys.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.liliudong.template.biz.mapper.sys.SysUserRoleMapper;
import com.liliudong.template.biz.service.sys.SysUserRoleService;
import com.liliudong.template.common.constant.ExMessage;
import com.liliudong.template.common.entity.sys.SysUserRole;
import com.liliudong.template.common.exception.BizException;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Set;

import static com.liliudong.template.common.entity.sys.table.SysUserRoleTableDef.SYS_USER_ROLE;

/**
 * SysUserRoleService
 *
 * @author liudo
 * @version 1.0
 * @project template-backend
 * @date 2024/7/31 12:35:29
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

    @Override
    public void saveBatchWithUserId(Long userId, Set<Long> roleIds) {
        if (CollectionUtil.isEmpty(roleIds)) {
            return;
        }
        if (Objects.isNull(userId)) {
            throw new BizException(ExMessage.USER_IS_EMPTY);
        }
        List<SysUserRole> sysUserRoles = roleIds.stream()
                .map(roleId -> {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setRoleId(roleId);
                    sysUserRole.setUserId(userId);
                    return sysUserRole;
                }).toList();
        saveBatch(sysUserRoles);
    }

    @Override
    public void removeByUserId(Long userId) {
        if (Objects.isNull(userId)) {
            throw new BizException(ExMessage.USER_IS_EMPTY);
        }
        remove(SYS_USER_ROLE.USER_ID.eq(userId));
    }

    @Override
    public List<Long> listRoleIdsByUserId(Long userId) {
        return queryChain()
                .select(SYS_USER_ROLE.ROLE_ID)
                .where(SYS_USER_ROLE.USER_ID.eq(userId))
                .list()
                .stream()
                .map(SysUserRole::getRoleId)
                .toList();
    }
}
